﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microhard.Core.Security;
using System.Configuration;
using System.Web;

namespace Microhard.WeixinMP.Unities
{
    public class SessionSecurity
    {
        public static string CreateToken(string weixinUserName)
        {
            string cleartext = weixinUserName + ConfigurationManager.AppSettings["WeixinSessionForEncrpt"];
            return HttpUtility.UrlEncode(EncDec.Encrypt(cleartext, ConfigurationManager.AppSettings["WeixinSessionKey"]));
        }

        public static bool IsAuthToken(string token, string weixinUserName)
        {
            string dectext = EncDec.Decrypt(token, ConfigurationManager.AppSettings["WeixinSessionKey"]);
            string cleartext = weixinUserName + ConfigurationManager.AppSettings["WeixinSessionForEncrpt"];
            if (dectext == cleartext)
                return true;
            return false;
        }

        public static string CreateWeixinMobileAppUrl(string weixinUserName, string url, Dictionary<string, string> urlParms)
        {
            string urlFormat = "{0}?WeixinToken={1}&WeixinName={2}&rc={3}&cov={4}";
            string token = SessionSecurity.CreateToken(weixinUserName);
            string finUrl = string.Format(urlFormat, url, token, weixinUserName, string.Empty, string.Empty);
            if (urlParms != null && urlParms.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (var k in urlParms)
                {
                    sb.Append("&" + k.Key + "=" + k.Value);
                }
                finUrl += sb.ToString();
            }
            return finUrl;
        }
    }
}
